<template>
    <div class="com-container">
        <!-- 折线图 -->
        <div ref="chartDom" class="com-chart"></div>
        <TableDetail v-if="detailDialog" :detailDialog="detailDialog" :info="info" @closeDialog="closeDialog"></TableDetail>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import * as echarts from 'echarts';
import TableDetail from './table-detail.vue';
import moment from 'moment';
@Component({
    name: 'LineChart',
    components: {
        TableDetail,
    },
})
// 折线图
export default class LineChart extends Vue {
    @Prop() data;
    @Prop() chartName: string;
    @Prop() date: any;
    chartInstance: any = null;
    title: string = '';
    // 监听消息走势详情
    detailDialog: boolean = false;
    info: any = {
        startDate: '',
        endDate: '',
    }; // 点击数据详情

    // 监听数据变化
    @Watch('data', { immediate: true, deep: true })
    onWatchData(newData) {
        // console.log(this.data, 'data--------------------');
        if (newData) {
            let that = this;
            this.$nextTick(() => {
                that.updateChart(newData);
            });
        }
    }

    @Watch('date', { immediate: true, deep: true })
    handleInfo() {
        this.info.startDate = this.date.startDate;
        this.info.endDate = this.date.endDate;
    }

    // 走势图点击
    handleLineClick(time: string) {
        console.log(time);
        this.info.title = this.data.title;
        this.info.unit = this.date.unit;
        this.info.startTime = '';
        this.info.endTime = '';
        if (this.date.unit == 'tenMinute') {
            if (time == '0000') {
                return;
            }
            let v02 = Number(time.substring(0, 2));
            let v24 = Number(time.substring(2, 4));
            // 最小刻度为10
            if (v24 >= 10) {
                v24 -= 10;
            } else {
                v02 -= 1;
                v24 = v24 + 60 - 10;
            }
            this.info.showStartTime = (v02 || '00') + '' + (v24 || '00');
            this.info.startTime = this.info.showStartTime + '00';
            this.info.showEndTime = time;
            this.info.endTime = time + '00';
        } else if (this.date.unit == 'hour') {
            this.info.startTime = Number(time.substring(0, 2)) - 1 + time.substring(2, 4) + '00';
            this.info.endTime = time + '00';
        } else if (this.date.unit == 'day') {
            this.info.startDate = time;
            this.info.endDate = time;
        } else if (this.date.unit == 'month') {
            this.info.startDate = time + '01';
            this.info.endDate = time + '31';
        } else if (this.date.unit == 'year') {
            this.info.startDate = time + '0101';
            this.info.endDate = time + '1231';
        }
        this.detailDialog = true;
    }

    mounted() {
        const xTitle = this.data.title;
        this.$set(window, xTitle, this.handleLineClick);
        this.initChart();
    }

    initChart() {
        this.chartInstance = echarts.init(this.$refs.chartDom);
        const xTitle = this.data.title;
        const initOption = {
            tooltip: {
                trigger: 'item',
                triggerOn: 'mousemove',
                enterable: true, // 鼠标是否可进入提示框浮层中
                confine: true, // 是否将 tooltip 框限制在图表的区域内
                extraCssText: 'z-index: 99;', // 额外附加到浮层的 css 样式
                position: function(p) {
                    // 其中p为当前鼠标的位置
                    return [p[0] + 15, p[1] - 15];
                },
                formatter: params => {
                    let color: any = '';
                    const name = params.name;
                    const seriesName = params.seriesName;
                    let marker = params.marker;
                    const value = params.value;
                    color = this.handleColor('tooltipContent');
                    marker = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background:linear-gradient(${this.handleColor(
                        'marker'
                    )});"></span>`;
                    return `${marker}${seriesName}:<span style="border-bottom:1px solid ${color};color:${color};margin:0 3px;font-size:8px;cursor:pointer;" onclick="${xTitle}('${name}')" >${value}${
                        this.chartName == '用户' ? '人' : '次'
                    }</span>&nbsp${this.getShowName(name)}`;
                },
                backgroundColor: 'rgba(239,239,239,0.7)',
                borderColor: 'rgba(0,0,0,0.1)',
                textStyle: {
                    color: 'rgba(0, 0, 0, 0.65)',
                },
                axisPointer: {
                    type: 'cross',
                    snap: true,
                    label: {
                        show: true,
                        formatter: param => {
                            console.log(param, 'param');
                            if (param.axisDimension == 'x') {
                                return this.getShowName(param.value);
                            }
                            return param.value.toFixed(2);
                        },
                        backgroundColor: '#6a7985',
                    },
                },
            },
            legend: {
                show: false,
            },

            grid: {
                left: '2%',
                right: '2%',
                top: '25%',
                bottom: '3%',
                height: '75%',
                containLabel: true,
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: this.data.xData,
                    axisLine: {
                        lineStyle: {
                            color: '#cccccc',
                        },
                    },
                    axisTick: {
                        show: true,
                        inside: true, // 坐标轴刻度朝内
                        length: 12,
                        alignWithLabel: true,
                        lineStyle: {
                            color: '#8ab09c',
                        },
                    },
                    axisLabel: {
                        color: '#8c8c8c',
                        interval: this.chartName == 'dailyVisible' ? 5 : 0,
                        formatter: ele => {
                            return this.getShowName(ele);
                        },
                    },
                },
            ],
            yAxis: [
                {
                    type: 'value',
                    splitNumber: 3,
                    axisLine: {
                        lineStyle: {
                            color: '#cccccc',
                        },
                    },
                    axisTick: {
                        show: false, // 不显示刻度
                    },
                    axisLabel: {
                        color: '#8c8c8c',
                        formatter: '{value}次',
                        showMinLabel: false,
                    },
                },
            ],
            series: [
                {
                    name: this.handleColor('name'),
                    type: 'line',
                    stack: 'Total',
                    areaStyle: {
                        normal: {
                            opacity: 1,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, this.handleColor('area')),
                        },
                    },
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, this.handleColor('circle')),

                            lineStyle: {
                                width: 1, // 折线宽度
                                color: this.handleColor('lineStyle'), // 改变折线颜色
                            },
                        },
                    },
                    smooth: true,
                    showSymbol: false,
                    emphasis: {
                        // focus: 'series',
                    },
                    data: this.data.data,
                },
            ],
        };

        this.chartInstance.setOption(initOption);
    }

    // 显示颜色
    handleColor(type: string) {
        const isDailyVisible = this.chartName == 'dailyVisible';
        const isL = this.chartName == '流量';
        if (type == 'tooltipContent') {
            return isDailyVisible ? '#46c27f' : isL ? '#e8973c' : '#9595fc';
        } else if (type == 'marker') {
            return isDailyVisible ? '#d2eedf,#4abc7e' : isL ? '#e9943f,#dcc70e' : '#7ba4f3,#87b1f2';
        } else if (type == 'lineStyle') {
            return isDailyVisible ? '#c8edd9' : isL ? '#f9e3b4' : '#d4defc';
        } else if (type == 'name') {
            return isDailyVisible ? '平均访问次数' : isL ? '访问次数' : '访问人数';
        } else if (type == 'area' || type == 'circle') {
            return isDailyVisible
                ? [
                      { offset: 0, color: '#f8fcfa' },
                      { offset: 1, color: '#c3e9d5' },
                  ]
                : isL
                ? [
                      { offset: 0, color: '#f8dac2' },
                      { offset: 1, color: '#f4edb0' },
                  ]
                : [
                      { offset: 0, color: '#d5d9fe' },
                      { offset: 1, color: '#c1dcfb' },
                  ];
        }
    }

    // 显示Label
    getShowName(ele: any) {
        if (this.date.unit == 'hour' || this.date.unit == 'tenMinute') {
            if (ele == '2400') {
                return '24:00';
            }
            return moment(ele, 'HHmm').format('HH:mm');
        } else if (this.date.unit == 'day') {
            const value = ele.substring(6, 8);
            return value + '日';
        } else if (this.date.unit == 'month') {
            const value = ele.substring(4, 6);
            return value + '月';
        } else if (this.date.unit == 'year') {
            return ele + '年';
        }
    }

    closeDialog() {
        this.detailDialog = false;
    }

    updateChart(e) {
        console.log(e, 'updateChart');
        const dataOption = {
            xAxis: { data: e.xData },
            series: [
                {
                    data: e.data,
                },
            ],
        };
        this.chartInstance.setOption(dataOption);
        // 点击事件
        this.chartInstance.on('click', param => {
            console.log(this.data, 'data');
            this.handleLineClick(param.name);
        });
    }
}
</script>

<style scoped>
.com-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.com-chart {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
